<template>
  <div>
    <!--面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 提示消息 -->
      <el-alert title="! 注意：只允许为第三级分类设置参数" type="warning">
      </el-alert>
      <!-- 选择商品分类 -->
      <el-form label-width="100px">
        <el-form-item label="选择商品分类: ">
          <el-cascader
            :options="categoriesListAll"
            :props="cateProps"
            v-model="selectKeys"
            @change="changeParamsId()"
          >
          </el-cascader>
        </el-form-item>
      </el-form>
      <!-- 标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleClick()">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="first">
          <!-- 添加参数按钮 -->
          <el-button
            type="primary"
            :disabled="buttonDis"
            @click="showAddManyDialog()"
            >添加参数</el-button
          >
          <!-- 属性表单 -->
          <el-table
            style="width: 100%"
            :border="true"
            :stripe="true"
            :data="paramsList"
          >
            <el-table-column width="50" type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="i"
                  v-for="(tag, i) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(i, scope.row)"
                >
                  {{ tag }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="#" width="50" type="index">
            </el-table-column>
            <el-table-column label="参数名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作" width="360">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParamsMany(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="second">
          <!-- 添加属性按钮 -->
          <el-button
            type="primary"
            :disabled="buttonDis"
            @click="showAddOnlyDialog()"
            >添加属性</el-button
          >
          <!-- 属性表单 -->
          <el-table
            style="width: 100%"
            :border="true"
            :stripe="true"
            :data="paramsList"
          >
            <el-table-column width="50" type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="i"
                  v-for="(tag, i) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(i, scope.row)"
                >
                  {{ tag }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="#" width="50" type="index">
            </el-table-column>
            <el-table-column label="参数名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作" width="360">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialogOnly(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParamsOnly(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加动态参数弹框 -->
    <el-dialog
      title="添加动态参数"
      :visible.sync="dialogVisibleAddMany"
      width="30%"
      @close="resetParamsAddMany()"
    >
      <el-form label-width="80px">
        <el-form-item label="添加参数">
          <el-input v-model="paramsAddMany"> </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="dialogVisibleAddMany = false">取 消</el-button>
        <el-button type="primary" @click="addParamsMany()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改动态参数弹框 -->
    <el-dialog
      title="修改动态参数"
      :visible.sync="dialogVisibleEditMany"
      width="30%"
      :model="paramsEditMany"
    >
      <el-form label-width="80px">
        <el-form-item label="修改参数">
          <el-input v-model="paramsEditMany.attr_name"> </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="dialogVisibleEditMany = false">取 消</el-button>
        <el-button type="primary" @click="editParamsMany()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加静态属性弹框 -->
    <el-dialog
      title="添加静态属性"
      :visible.sync="dialogVisibleAddOnly"
      width="30%"
      @close="resetParamsAddOnly()"
    >
      <el-form label-width="80px">
        <el-form-item label="静态属性">
          <el-input v-model="paramsAddOnly"> </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="dialogVisibleAddOnly = false">取 消</el-button>
        <el-button type="primary" @click="addParamsOnly()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改静态属性弹框 -->
    <el-dialog
      title="修改静态属性"
      :visible.sync="dialogVisibleEditOnly"
      width="30%"
      :model="paramsEditOnly"
    >
      <el-form label-width="80px">
        <el-form-item label="静态属性">
          <el-input v-model="paramsEditOnly.attr_name"> </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="dialogVisibleEditOnly = false">取 消</el-button>
        <el-button type="primary" @click="editParamsOnly()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //所有商品分类列表
      categoriesListAll: [],
      selectKeys: [],
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover",
      },
      activeName: "first",
      paramsInfo: {
        id: 0,
        sel: "many",
      },
      //属性列表
      paramsList: [],
      buttonDis: true,
      //添加动态参数
      paramsAddMany: "",
      dialogVisibleAddMany: false,
      //修改动态参数
      paramsEditMany: {},
      dialogVisibleEditMany: false,
      //添加静态属性
      paramsAddOnly: "",
      dialogVisibleAddOnly: false,
      //修改静态属性
      paramsEditOnly: {},
      dialogVisibleEditOnly: false,
    };
  },
  created() {
    this.getAllCategories();
  },
  methods: {
    //获取所有商品分类
    async getAllCategories() {
      const { data: res } = await this.$http.get("categories");
      console.log(res);
      if (res.meta.status != 200) return this.$message.error("获取失败");
      // this.$message.success(res.meta.msg);
      this.categoriesListAll = res.data;
      this.total = res.data.length;
    },
    //提交paramsInfo.id
    changeParamsId() {
      // console.log(this.selectKeys);
      this.paramsInfo.id = this.selectKeys[2];
      this.buttonDis = false;
      this.getParamsList();
    },
    //确定动态或静态
    handleClick() {
      if (this.activeName === "first") {
        this.paramsInfo.sel = "many";
        this.getParamsList();
        return;
      } else {
        this.paramsInfo.sel = "only";
        this.getParamsList();
        return;
      }
    },
    //获取参数列表
    async getParamsList() {
      const { data: res } = await this.$http.get(
        `categories/${this.paramsInfo.id}/attributes`,
        {
          params: this.paramsInfo,
        }
      );
      console.log(res);
      if (res.meta.status != 200) return this.$message.error("获取失败");
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        item.inputVisible = false;
        item.inputValue = "";
      });
      console.log(res);
      this.paramsList = res.data;
    },
    //展示标签输入框
    showInput(row) {
      row.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //发送编辑提交参数
    async saveAttrVals(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.paramsInfo.id}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" "),
        }
      );
      // console.log(res);
      if (res.meta.status !== 200) return this.$message.error("更新失败");
    },
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = "";
      row.inputVisible = false;
      //发送保存这次操作请求
      this.saveAttrVals(row);
    },
    //删除对应参数
    handleClose(i, row) {
      row.attr_vals.splice(i, 1);
      this.saveAttrVals(row);
    },
    //显示增加动态参数弹窗
    showAddManyDialog() {
      this.dialogVisibleAddMany = true;
    },
    //显示增加静态属性弹窗
    showAddOnlyDialog() {
      this.dialogVisibleAddOnly = true;
    },
    //重置增加动态弹窗的内容
    resetParamsAddMany() {
      this.addParamsMany = "";
    },
    //重置增加静态属性的内容
    resetParamsAddOnly() {
      this.addParamsOnly = "";
    },
    //发送增加动态参数请求
    async addParamsMany() {
      if (this.paramsAddMany.trim().length === 0)
        return this.$message.error("请输入参数名");
      const { data: res } = await this.$http.post(
        `categories/${this.paramsInfo.id}/attributes`,
        {
          attr_name: this.paramsAddMany,
          attr_sel: this.paramsInfo.sel,
          attr_vals: "",
        }
      );
      console.log(res);
      if (res.meta.status !== 201) return this.$message.error("增加失败");
      this.dialogVisibleAddMany = false;
      this.paramsAddMany = "";
      this.getParamsList();
    },
    //发送增加静态属性请求
    async addParamsOnly() {
      if (this.paramsAddOnly.trim().length === 0)
        return this.$message.error("请输入属性名");
      const { data: res } = await this.$http.post(
        `categories/${this.paramsInfo.id}/attributes`,
        {
          attr_name: this.paramsAddOnly,
          attr_sel: this.paramsInfo.sel,
          attr_vals: "",
        }
      );
      console.log(res);
      if (res.meta.status !== 201) return this.$message.error("增加失败");
      this.dialogVisibleAddOnly = false;
      this.paramsAddOnly = "";
      this.getParamsList();
    },
    //显示修改动态参数弹窗
    showEditDialog(row) {
      this.paramsEditMany = row;
      this.dialogVisibleEditMany = true;
    },
    //显示修改静态属性弹窗
    showEditDialogOnly(row) {
      this.paramsEditOnly = row;
      this.dialogVisibleEditOnly = true;
    },
    //发送修改动态参数请求
    async editParamsMany() {
      const { data: res } = await this.$http.put(
        `categories/${this.paramsInfo.id}/attributes/${this.paramsEditMany.attr_id}`,
        {
          attr_name: this.paramsEditMany.attr_name,
          attr_sel: this.paramsEditMany.attr_sel,
          attr_vals: this.paramsEditMany.attr_vals.join(" "),
        }
      );
      // console.log(res);
      if (res.meta.status !== 200) return this.$message.error("更新失败");
      this.dialogVisibleEditMany = false;
      this.getParamsList();
    },
    //发送修改静态属性请求
    async editParamsOnly() {
      const { data: res } = await this.$http.put(
        `categories/${this.paramsInfo.id}/attributes/${this.paramsEditOnly.attr_id}`,
        {
          attr_name: this.paramsEditOnly.attr_name,
          attr_sel: this.paramsEditOnly.attr_sel,
          attr_vals: this.paramsEditOnly.attr_vals,
        }
      );
      console.log(res);
      if (res.meta.status !== 200) return this.$message.error("更新失败");
      this.dialogVisibleEditOnly = false;
      this.getParamsList();
    },
    //删除动态参数
    deleteParamsMany(row) {
      this.$confirm("此操作将永久删除该参数, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${this.paramsInfo.id}/attributes/${row.attr_id}`
          );
          // console.log(res);
          if (res.meta.status !== 200) return this.$message.error("删除失败");
          this.$message.success("删除成功");
          this.getParamsList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //删除静态属性
    deleteParamsOnly(row) {
      this.$confirm("此操作将永久删除该属性, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${this.paramsInfo.id}/attributes/${row.attr_id}`
          );
          // console.log(res);
          if (res.meta.status !== 200) return this.$message.error("删除失败");
          this.$message.success("删除成功");
          this.getParamsList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>
<style lang='less' scoped>
.input-new-tag {
  width: 160px;
}
</style>